package org.jeecg.modules.car.controller;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.RedisKeyConstant;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.StringUtils;
import org.jeecg.common.util.sms.SmsUtil;
import org.jeecg.entity.car.CarInfo;
import org.jeecg.entity.car.CarParkingRecord;
import org.jeecg.enums.SmsBusinessTypeEnum;
import org.jeecg.model.charge.reqvo.DayReportReqVo;
import org.jeecg.model.charge.resvo.DayReportRespVo;
import org.jeecg.modules.car.entity.CarParkInfo;
import org.jeecg.modules.car.service.*;
import org.jeecg.modules.car.service.impl.ForeignCarShParkingService;
import org.jeecg.modules.car.utils.ComUtil;
import org.jeecg.modules.system.entity.SmsEntity;
import org.jeecg.modules.system.entity.SysSms;
import org.jeecg.modules.system.service.ISysSmsService;
import org.jeecg.vo.car.ForeignCarShLeaveReq;
import org.jeecg.vo.car.ForeignCarShResendReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Description: 车辆Api接口
 * @Author: liurui
 * @Date:   2020-11-08
 * @Version: V1.0
 */
@Slf4j
@Api(tags="车辆Api接口")
@RestController
@RequestMapping("/api/car")
public class CarDataApiController {
    @Resource
    ICarMerchantService carMerchantService;
    @Resource
    ICarInfoService carInfoService;
    @Resource
    ISysSmsService sysSmsService;
    @Autowired
    private ICarOrderService carOrderService;
    @Autowired
    private ForeignCarShParkingService shParkingService;
    @Autowired
    private ICarParkInfoService parkInfoService;
    @Autowired
    private ICarParkingRecordService parkingRecordService;
    @Autowired
    private RedisUtil redisUtil;

    @GetMapping(value = "/carList")
    public Result<Page<CarInfo>> carList(HttpServletRequest request, @RequestParam(name = "roomId") String roomId,
                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize
    ) {

        Result<Page<CarInfo>> result = new Result<Page<CarInfo>>();
        try {
            Page<CarInfo> page = new Page<CarInfo>(pageNo, pageSize);
            CarInfo carInfo = new CarInfo();
            carInfo.setRoomId(roomId);
            List<CarInfo> list = carInfoService.findPage(page,carInfo);
            page.setRecords(list);
            result.setSuccess(true);
            result.setResult(page);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }


    @ApiOperation(value="月卡充值日收款汇总报表-列表查询", notes="月卡充值日收款汇总报表-列表查询")
    @PostMapping(value = "/carFindGroupList")
    public List<DayReportRespVo> findGroupList(@RequestBody DayReportReqVo dayReportReqVo,@RequestHeader("tenantId") String tenantId){
        log.info("月卡充值日收款汇总报表被远程调用参数：{}",dayReportReqVo);
        dayReportReqVo.setTenantId(tenantId);
        return carOrderService.apiFindGroupList(dayReportReqVo);
    }

    @AutoLog(value = "定时赠送商家金额")
    @ApiOperation(value="定时赠送商家金额", notes="定时赠送商家金额")
    @PostMapping(value = "/refreshExpiredDerate")
    public Result<String> refreshExpiredDerate() {
        try {
            return carMerchantService.addAllDonateAmount();
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return Result.error(e.getMessage());
        }
    }

    @AutoLog(value = "定时清空商家赠送金额")
    @ApiOperation(value="定时清空商家赠送金额", notes="定时清空商家赠送金额")
    @PostMapping(value = "/clearDonateAmount")
    public Result<String> clearDonateAmount() {
        try {
            carMerchantService.clearAllDonateAmount();
            return Result.ok();
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return Result.error(e.getMessage());
        }
    }

    @AutoLog(value = "月卡到期短信通知")
    @ApiOperation(value = "月卡到期短信通知", notes = "月卡到期短信通知")
    @PostMapping(value = "/carExpireSms")
    public Result<String> carExpireSms(){
        try {
            List<CarInfo> list = carInfoService.getAllOrderCarList(SmsBusinessTypeEnum.SMS_CAR_001.getCode());
            for (CarInfo temp: list){
                if (temp.getSysSmsConfig() == null){
                    log.warn("月卡到期短信通知基础参数未设置！");
                    continue;
                }
                if (temp.getSmsDay() == null){
                    log.warn("月卡到期短信通知未设置提醒天数或未开通短信提醒！");
                    continue;
                }
                int day = ComUtil.diffDays(new Date(), temp.getLocalEndTime());
                // 提前两天通知发送短信
                if (day == temp.getSmsDay()){
                    SmsEntity smsEntity = SmsUtil.sendSmsWithConfig(temp.getSysSmsConfig(),temp.getMobile(),"date", DateUtils.date2Str(temp.getLocalEndTime(),DateUtils.datetimeFormat),"plateNum",temp.getCarNo());
                    String status = "2";
                    if ("OK".equals(smsEntity.getMessage())){
                        status = "1";
                    }
                    SysSms sysMessage = new SysSms();
                    sysMessage.setId(IdWorker.getIdStr());
                    sysMessage.setEsType(1);
                    sysMessage.setTenantId(temp.getTenantId());
                    sysMessage.setEsContent(smsEntity.getContent());
                    sysMessage.setProjectId(temp.getProjectId());
                    sysMessage.setEsReceiver(temp.getMobile());
                    sysMessage.setIsBilling(1);
                    sysMessage.setBusinessId(temp.getId());
                    sysMessage.setBusinessType(SmsBusinessTypeEnum.SMS_CAR_001.getCode());
                    sysMessage.setEsTitle(SmsBusinessTypeEnum.SMS_CAR_001.getDesc());
                    sysMessage.setEsSendStatus(status);
                    sysMessage.setEsSendTime(new Date());
                    sysSmsService.addMessage(sysMessage);
                }
            }
            return Result.ok();
        }catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }

    @AutoLog(value = "上海公共平台心跳检测")
    @ApiOperation(value="上海公共平台心跳检测", notes="上海公共平台心跳检测")
    @PostMapping(value = "/shParkingHeartBeat")
    public void shParkingHeartBeat() {
        try {
            shParkingService.heartbeatBatch();
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
    }


    @AutoLog(value = "上海公共平台数据补传")
    @ApiOperation(value="上海公共平台数据补传", notes="上海公共平台数据补传")
    @PostMapping(value = "/shParkingResend")
    public void shParkingResend() {
        try {
            List<CarParkInfo> parkInfoList =  parkInfoService.findShParking();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.DAY_OF_MONTH,-1);
            for (CarParkInfo carParkInfo:parkInfoList){
                log.info("数据补传--车场:{}",carParkInfo.getParkName());
                List<CarParkingRecord> recordList =  parkingRecordService.selectNotSyncShParking(carParkInfo.getId(),DateUtils.date2Str(calendar.getTime(),DateUtils.date_sdf));
                if (recordList.size() <= 0) continue;
                ForeignCarShResendReq resendReq = new ForeignCarShResendReq();
                List<String> arriveIds = new ArrayList<>();
                List<String> leaveIds = new ArrayList<>();
                for (CarParkingRecord carParkingRecord:recordList){
                    ForeignCarShLeaveReq leaveReq = new ForeignCarShLeaveReq();
                    leaveReq.setParkingId(carParkInfo.getSuperviseParkingId());
                    leaveReq.setAppId(carParkInfo.getSuperviseAppId());
                    leaveReq.setPassword(carParkInfo.getSupervisePassword());
                    if (carParkingRecord.getEnterType() != 0){
                        leaveReq.setParkType(1); //1:临停
                    } else if (StringUtils.isBlank(carParkingRecord.getCarId())){
                        leaveReq.setParkType(1); //1:临停
                    } else {
                        leaveReq.setParkType(2); //2:月卡
                    }
                    leaveReq.setPlateId(carParkingRecord.getCarNo());
                    leaveReq.setLaneType(1);
                    leaveReq.setVehicleType(1);
                    String counterFreeKey = RedisKeyConstant.CAR_COUNTER_FREE + carParkInfo.getId(); //空闲车位
                    Object free = redisUtil.get(counterFreeKey);
                    leaveReq.setFreeBerth(free ==null?0:(int)free);
                    if (!carParkingRecord.getArrivedStatus()){ //入场未上传
                        resendReq.getArriveList().add(leaveReq);
                        arriveIds.add(carParkingRecord.getId());
                    }
                    if (!carParkingRecord.getLeaveStatus()){  //离场未上传
                        leaveIds.add(carParkingRecord.getId());
                        leaveReq.setPayType("unknown"); //其他
                        Calendar carEnter = Calendar.getInstance();
                        carEnter.setTime(carParkingRecord.getEntranceTime());
                        Calendar carLeave = Calendar.getInstance();
                        carLeave.setTime(carParkingRecord.getExitTime());
                        leaveReq.setParkingTime((int)(carLeave.getTimeInMillis() - carEnter.getTimeInMillis())/1000);
                        leaveReq.setPayMoney(carParkingRecord.getPayMoney() * 100 );
                        resendReq.getLeaveList().add(leaveReq);
                    }
                }
                boolean res = shParkingService.resend(resendReq);
                //更新状态
                if (res){
                    if (arriveIds.size() > 0){
                        parkingRecordService.update(Wrappers.<CarParkingRecord>update().lambda().set(CarParkingRecord::getArrivedStatus,true)
                                .in(CarParkingRecord::getId,arriveIds).eq(CarParkingRecord::getTenantId,carParkInfo.getTenantId()));
                    }
                    if (leaveIds.size() >0){
                        parkingRecordService.update(Wrappers.<CarParkingRecord>update().lambda().set(CarParkingRecord::getLeaveStatus,true)
                                .in(CarParkingRecord::getId,leaveIds).eq(CarParkingRecord::getTenantId,carParkInfo.getTenantId()));
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
    }



}
